package com.sinosoft.web;

import com.sinosoft.domain.Account;
import com.sinosoft.domain.AuthResponse;
import com.sinosoft.domain.AuthResponseCode;
import com.sinosoft.service.JwtService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @author loujiang
 * @date 2021/1/2 2:53 下午
 * @NOTE:
 */
@RestController
@Slf4j
public class AuthController  {


    @Autowired
    private JwtService jwtService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    @ResponseBody
    public AuthResponse login(@RequestParam("username") String username, @RequestParam("password") String password) {
        Account account = Account.builder().username(username).build();
        //TODO 验证 username + password
        String token = jwtService.token(account);
        account.setToken(token);
        account.setRefreshToken(UUID.randomUUID().toString());
        redisTemplate.opsForValue().set(account.getRefreshToken(), account);
        return AuthResponse.builder().account(account).code(AuthResponseCode.SUCCESS).build();
    }

    /**
     * 刷新token
     *
     * @param refreshToken
     * @return
     */
    @PostMapping("/refresh")
    @ResponseBody
    public AuthResponse refresh(@RequestParam("refresh") String refreshToken) {
        Account account = (Account) redisTemplate.opsForValue().get(refreshToken);
        if (redisTemplate.opsForValue().get(refreshToken) == null) {
            return AuthResponse.builder().code(AuthResponseCode.USER_NOT_FOUND).build();
        }
        String jwt = jwtService.token(account);
        account.setToken(jwt);
        account.setRefreshToken(UUID.randomUUID().toString());
        redisTemplate.delete(refreshToken);
        redisTemplate.opsForValue().set(account.getRefreshToken(), account);
        return AuthResponse.builder().account(account).code(AuthResponseCode.SUCCESS).build();
    }

    @RequestMapping("/verify")
    public AuthResponse verify(@RequestParam("token") String token, @RequestParam("username") String username) {

        if (jwtService.verify(token, username)) {
            return AuthResponse.builder().code(AuthResponseCode.SUCCESS).build();
        } else {
            return AuthResponse.builder().code(AuthResponseCode.VERIFY_FAIL).build();
        }

    }


}
